package com.digiregistry.api.wrapper.util;

import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.httpclient.methods.FileRequestEntity;

import com.digiregistry.api.wrapper.UploadProgressListener;

public class ProgressFileRequestEntity extends FileRequestEntity {

	private UploadProgressListener listener;
	private long total;
	
	public ProgressFileRequestEntity(File file, String contentType, UploadProgressListener listener) {
		super(file, contentType);
		this.listener = listener;
		this.total = file.length();
	}

	@Override
	public void writeRequest(OutputStream out) throws IOException {
		if (listener == null)
			super.writeRequest(out);
		else
			super.writeRequest(new CountingOutputStream(out, listener, total));
	}
	
    public static class CountingOutputStream extends FilterOutputStream {

        private final UploadProgressListener listener;
        private long transferred;
        private long total;

        public CountingOutputStream(final OutputStream out,
                final UploadProgressListener listener, final long total) {
            super(out);
            this.listener = listener;
            this.transferred = 0;
            this.total = total;
        }


		@Override
        public void write(byte[] b, int off, int len) throws IOException {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.progress(this.transferred, this.total);
        }

		@Override
        public void write(int b) throws IOException {
            out.write(b);
            this.transferred++;
            this.listener.progress(this.transferred, this.total);
        }
    }
	
}
